package com.zh.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.QueryPageParam;
import com.zh.common.Result;
import com.zh.entity.Goods;
import com.zh.entity.Record;
import com.zh.entity.recordResult.RecordName;
import com.zh.mapper.RecordMapper;
import com.zh.service.GoodsService;
import com.zh.service.RecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zh
 * @since 2025-04-07
 */
@Service
public class RecordServiceImpl extends ServiceImpl<RecordMapper, Record> implements RecordService {
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private GoodsService goodsService;

    @Override
    public Result listBySubquery(QueryPageParam queryPageParam) {
        HashMap param = queryPageParam.getParam();
        String goodsName = (String) param.get("goodsName");
        String goodsTypeName = (String) param.get("goodsTypeName");
        String storageName = (String) param.get("StorageName");

        // 创建分页对象
        Page<RecordName> page = new Page<>(
                queryPageParam.getPageNum(),
                queryPageParam.getPageSize()
        );

        // 构建 Wrapper
        QueryWrapper<RecordName> wrapper = new QueryWrapper<>();
        if (goodsName != null && !goodsName.isEmpty()) {
            wrapper.like("g.name", goodsName);
        }
        if (goodsTypeName != null && !goodsTypeName.isEmpty()) {
            wrapper.like("gt.name", goodsTypeName);
        }
        if (storageName != null && !storageName.isEmpty()) {
            wrapper.like("s.name", storageName);
        }

        // 调用自定义的子查询（分页查询）
        IPage<RecordName> result = recordMapper.listBySubqueryPage(page, wrapper);

        // 返回分页结果
        return Result.success(result.getRecords(), result.getTotal());
    }

    @Override
    public Result saveRecord(Record record) {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql("count = count + " + record.getCount()) // 直接使用SQL原子操作
                .eq("id", record.getGoodsId());
        boolean updateSuccess = goodsService.update(updateWrapper);
        this.save(record);
        return Result.success(updateSuccess, 0L);
    }

}

